package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.Book;
import com.example.demo.entity.User;
import com.example.demo.mapper.BookMapper;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/***
 ** Create by Wedream on 2021/7/16
 */
@RestController
@RequestMapping("/book")
public class BookController {

    @Resource
    BookMapper BookMapper;

    @PostMapping  //增
    public Result<?> save(@RequestBody Book Book) {
        BookMapper.insert(Book);
        return Result.success();
    }

    @DeleteMapping("/{id}") //删
    public Result<?> delete(@PathVariable long id) {
        BookMapper.deleteById(id);
        return Result.success();
    }

    @GetMapping //查
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "",required = false) String search) {

        LambdaQueryWrapper<Book> wrapper = Wrappers.<Book>lambdaQuery();
        if(StrUtil.isNotBlank(search)) {
           wrapper.like(Book::getName,search);
        }
        Page<Book> BookPage = BookMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(BookPage);
    }

    // 导出Excel
    @ResponseExcel(name = "book", sheet = "book")
    @GetMapping("/downloadExcel")
    public List<Book> DownloadExcel(@RequestParam(defaultValue = "1") Integer pageNum,
                                    @RequestParam(defaultValue = "1000") Integer pageSize,
                                    @RequestParam(defaultValue = "",required = false) String search) {

        LambdaQueryWrapper<Book> wrapper = Wrappers.<Book>lambdaQuery();
        if(StrUtil.isNotBlank(search)) {
            wrapper.like(Book::getName,search);
        }
        Page<Book> bookPage = BookMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        List<Book> records = bookPage.getRecords();
        return records;
    }

    @PutMapping //改
    public Result<?> update(@RequestBody Book Book) {
        BookMapper.updateById(Book);
        return Result.success();
    }
}
